$(function() {
//Declare variable
	var  customerType= $( "#type_01"),
		cboUnit=$("#cboUnit"),
		cboProductType=$("#cboProductType"),
		cboProductList=$("#cboProductList"),
		btnSearchCustomer=$("#btnSearchCustomer"),
		btndlgSearch=$("#btndlgSearch"),
		dlg_custCode=$("#txtCustCode"),
		dlg_custName=$("#txtCustName"),
		dlg_custCardId=$("#txtCardID"),
		main_custcode=$("#Main_Cust_Code"),
		main_custname=$("#Main_Cust_Name"),	
		ButtonCustomerHistory=$("#btnCustHistory"),
		ButtonCustomerService=$("#btnCustService"),
		ButtonSmartPurse=$("#btnSmartPurse"),
		ButtonUpdateCustomer=$("#btnEditCustomer"),
		ButtonCancelBill=$("#btnBill"),		
		loading=$("#load"),
		SmartCardNo=$("#SmartCardNo"),
		SmartAmount=$("#SmartAmount"),		
		allFields = $( [] ).add( dlg_custCode ).add( dlg_custName ),
		SmartFields=$([]).add(SmartCardNo).add(SmartAmount),	
		tips = $( ".validateTips" ),
		button_name="",
		url="a_main.php", 
		Is_Add_Active=false,
		rowSelect="",
		ID="",
		modeLogin="discount",
 		rowSelect="",
		m_discount={},
		isClick=false,
		m_CustomerID=0,
		o_product_list={};
		
		//For collect ex discount
		var objExDiscount=[];	
		var objSelectDiscount=[];
		
		var  Code= $( "#Code" ),FirstName = $( "#FirstName" ),	LastName = $( "#LastName" ),
			Birthday = $("#Birthday"),Address=$("#Address"),Email=$("#Email"),Telephone=$("#Telephone");
		var addCustFields = $( [] ).add( Code ).add(FirstName).add(LastName).add(Birthday).add(Address).add(Telephone).add($("#CardID"));

		//Load First page
		loadDataToControls();	
		
		//*******************************
		//Event Handler
		//*******************************
		 $("#giftAmt").live('click',function(){
		 //alert('dd');
			$(this).select();
			$(this).numeric();
		});
		
		//Select card Type 
		$("#cboCardType").change(function(){
			var cardid=$("#cboCardType").val();
			if (cardid > -1){
				$.get(url,{'cval':cardid},function(data){
					var obj = eval("("+data+")");
					$("#iDiscount2").attr('innerHTML', obj['Discount'] );
					$("#iDiscount2_type").attr('innerHTML', obj["Type_Dis"]);
 
				});
			}else{
				$("#iDiscount2").attr('innerHTML', '0');
 
			}
		});
		
		//Select Discount Type popup
		$("#cboDisType").change(function(){
			var dataset={};
			 if ($("#cboDisType").val()==0){
				//credit card
				dataset = {"c":"cc"};
			}else{
				//coupon
				dataset = {"c":"cp"};
			}
			//0 = CrditCard , 1= coupon
			$("#cboCardType").find('option').remove();
			$.get(url, dataset,function(data){
				 var obj=eval('('+data+')');
				 if (obj!=null) {
					$.each(obj, function(index, text) {
						$("#cboCardType").append(
							$('<option></option>').val(index).html(text)
						 );
					});
				}
			});		
			$("#cboCardType").append($('<option></option>').val(-1).html('---Select ---'));
		});

 		//Select Product type destroy
		cboProductType.change(function(){
			var dataset={};
			//Add Loading
			loading.addClass("info_loading").fadeIn("200");
			 
			 if (cboProductType.val()==1){
				dataset = {"c":"rp"};
			 }else if (cboProductType.val()==2) {
				dataset = {"c":"tr"};
			 }else if (cboProductType.val()==3) {
				dataset = {"c":"s"};
			 }else if (cboProductType.val()==4) {
				dataset = {"c":"co"};
			 }

			$( ".ui-autocomplete-input" ).val('');
			cboProductList.find('option').remove();	
		
			$.get(url, dataset,function(data){
				 var obj=eval('('+data+')');
				 if (obj!=null) {
					$.each(obj, function(index, text) {
						cboProductList.append(
							$('<option></option>').val(text).html(index)
						 );
					});
				}
			});	
			
			//loading 
			loading.removeClass("info_loading");			
		});
		
		//Discount Type in popup
		$("input:radio[name=discounttype]").click(function(){
			// 1: user , 2:credit card , 3:Gift Voucher
		
			var chk_type=$("input:radio[name='discounttype']:checked").val();
				if (chk_type==1){
					$("#spDiscount").show();
					$("#spCard").hide();
					$("#spGiftVoucher").hide();
				}
				else if (chk_type==3){
					$("#spDiscount").hide();
					$("#spCard").hide();
					$("#spGiftVoucher").show();
					
				}
				else 
				{
					$("#spDiscount").hide();
						$("#spGiftVoucher").hide();
					$("#spCard").show();
 
				}
		});
		
		//Customer Type Click
		$("input:radio[name='CustType']").click(function(){
				 
			var chk_val=$("input:radio[name='CustType']:checked").val();
			 //1:member , 2:non-member
			 if (chk_val==2){
				$("#tr_member,#tr_remain,#tr_remain2").hide('slow');			
				if ($("#IspayOther").attr('checked')){
					$("#tr_remain2").hide('slow');
				} 
				cboProductType.find('option').remove();
				$( ".ui-autocomplete-input" ).val('');
				cboProductList.find('option').remove();
				$.get(url, {"c":"tn"},function(data){	
					//alert(data);
					var obj=eval('('+data+')');
					if (obj!=null){
						$.each(obj, function(index, text) {
							cboProductType.append(
								$('<option></option>').val(index).html(text)
							 );
						});
					}
				});
				//Load Product List
				$.get(url, {"c":"rp"},function(data){
					var obj=eval('('+data+')');
					if (obj!=null){
						$.each(obj, function(index, text) {
							cboProductList.append(
								$('<option></option>').val(text).html(index)
							 );
						});
					}
				});
				
			}
			 else{
				$("#tr_member,#tr_remain").show('slow');
				if ($("#IspayOther").attr('checked')){
					$("#tr_remain2").show('slow');
				}

				cboProductType.find('option').remove();
				$( ".ui-autocomplete-input" ).val('');
				cboProductList.find('option').remove();
				$.get(url, {"c":"t"},function(data){	
					//alert(data);
					var obj=eval('('+data+')');
					if (obj!=null){
						$.each(obj, function(index, text) {
							cboProductType.append(
								$('<option></option>').val(index).html(text)
							 );
						});
					}
				});	

				//Load Product List
				$.get(url, {"c":"rp"},function(data){
					var obj=eval('('+data+')');
					if (obj!=null){
						$.each(obj, function(index, text) {
							cboProductList.append(
								$('<option></option>').val(text).html(index)
							 );
						});
					}
				});				
			}
		});
		
		//Payment TYpe Click
		$("input:radio[name='PayType']").click(function(){
			//1:cash, 2:CreditCard, 3:Smart Purse
			var vPayType=$("input:radio[name='PayType']:checked").val();
			
			if (vPayType=="1"){
				$("#tr_cardName").hide();
				$("#tr_change").show();
			}else if (vPayType=="2"){
				$("#tr_cardName").show();
				$("#tr_change").hide();
				$("#lblcardNo").attr('innerHTML','Card No. :');
				
			}else if (vPayType=="3"){
				$("#tr_change").hide();
				$("#tr_cardName").show();
				$("#lblcardNo").attr('innerHTML','Coupon No. :');
			}
			if ($("#IspayOther").attr('checked')){
				if (vPayType=="1"){
					$("#Card2").removeAttr('disabled');
					$("#Card2").attr('checked','checked');
					$("#Cash2").attr('disabled','disabled');
					
					changePayType2(2);
				}else if ((vPayType=="2") || (vPayType=="3")){
					$("#Cash2").removeAttr('disabled');
					$("#Cash2").attr('checked','checked');
					$("#Card2").attr('disabled','disabled');
					changePayType2(1);
				}
			}
		});
		
		//Payment TYpe 2 Click
		$("input:radio[name='PayType2']").click(function(){
			//1:cash, 2:CreditCard, 3:Smart Purse
			var vPayType=$("input:radio[name='PayType2']:checked").val();
			changePayType2(vPayType);
			
		});
		function changePayType2(vPayType){
		
			if (vPayType=="1"){
				$("#tr_cardName2").hide();
				$("#tr_change2").show();
			}else if (vPayType=="2"){
				$("#tr_cardName2").show();
				$("#tr_change2").hide();
				$("#lblcardNo2").attr('innerHTML','Card No. :');
				
			}else if (vPayType=="3"){
				$("#tr_change2").hide();
				$("#tr_cardName2").show();
				$("#lblcardNo2").attr('innerHTML','Coupon No. :');
			}
		}
		//Other Payment 
		$("#IspayOther").click(function(){
			 if ($("#IspayOther").attr('checked')){
				$(".pay2").fadeIn('slow');
				var t_pay=$("input:radio[name='PayType']:checked").val();
				//alert(t_pay);
				if (t_pay=="1"){
					$("#Card2").removeAttr('disabled');
					$("#Card2").attr('checked','checked');
					$("#Cash2").attr('disabled','disabled');
					
					changePayType2(2);
				}else if ((t_pay=="2") || (t_pay=="3")){
					$("#Cash2").removeAttr('disabled');
					$("#Cash2").attr('checked','checked');
					$("#Card2").attr('disabled','disabled');
					changePayType2(1);
				}
				//$("#tr_cardName2").hide();
				//$("#Cash2").attr('checked','checked');
				//Clear 
				$("#txtPayAmt2,#txtChangeAmt2").val('0');
				//$("#txtRemainAmt2").val($("#txtRemainAmt").val());
				$("#txtPayAmt2").val($("#txtRemainAmt").val());
				
				var chk_val=$("input:radio[name='CustType']:checked").val();
				
				if (chk_val==2){
					$("#tr_remain2").hide();
				}
				
			 }else{
			 	$(".pay2").fadeOut('slow');
			 }
		});
		
		//Text change 
		$("#txtRemainAmt").live('change',function(){
			var remainAmt=$(this).val().replace(',','').replace(',','');
			var isOtherPay=$("#IspayOther").attr('checked');
			
			if (isOtherPay){
				$("#txtPayAmt2").val($("#txtRemainAmt").val());
				$("#txtRemainAmt2").val("0");
			}
				//$("#txtRemainAmt2").val($("#txtRemainAmt").val());
			
			if ( parseFloat(remainAmt) > 0){
				$("#IspayOther").removeAttr('disabled');
			}else{
				$("#IspayOther").attr('disabled','disabled');
				$("#IspayOther").removeAttr('checked');
				$(".pay2").fadeOut('slow');
				
			}
		});
		
		// button customer search click
		btnSearchCustomer.click(function(){
			$( "#dialog-form" ).dialog({'title':"Search Customer"});
			$( "#dialog-form" ).dialog( "open" );
			$( "#dialog-form" ).dialog( "option","buttons",{
				"Selected":function(){
					allFields.removeClass( "ui-state-error" );
					if ( checkRequireControl('create') ) {
						callAjax(setData(),0); // call ajax function for add new data
						$( this ).dialog( "close" );
					}
				},
				"Cancel":function(){$( this ).dialog( "close" );}
			});		
		});
		
		//button dialog search
		btndlgSearch.click(function(){
			if (checkInputControl()){
				//alert(dlg_custName.val());
				var dataset={'m':'cust2','var':{'code':dlg_custCode.val(),'name':dlg_custName.val(),'cardid':dlg_custCardId.val()}};
				$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: dataset,
					success: function(data){
						//alert(data);
						var m=eval("("+data+")");
						$( "#tbSearchCust tbody tr" ).remove();
						//Insert data to first row.
						$( "#tbSearchCust tbody:first" ).prepend( m['data'] ); 
						//set rows count
						$("#iCount").attr("innerHTML", m['rows']);
					}
				});
				return false;
			}else{
				return false;
			}
		});
		
		//Table mouse hover
		 $( "#tbSearchCust tbody tr" ).live('hover',function(){
			$(this).toggleClass('crm-row-highlight');
		});
		
		$("#btnSelectCust").live('click',function(){
				var custCode=$(this).parent().parent().find("td").eq(2).html();
				var custName=$(this).parent().parent().find("td").eq(3).html();
				var custID=$(this).parent().parent().find("td").eq(1).html();


				//alert($(this).parent().parent().find("td").eq(9).html() + '  '  + $(this).parent().parent().find("td").eq(10).html() );
				
				main_custcode.val(custCode);
				main_custname.val(custName);
				//Fixed 
				m_CustomerID = custID;
				//>>
				
				$("#custid").val(custID);
				
				$("#CustCode").val(custCode);
				$("#CustName").val(custName);
				
				ButtonCustomerHistory.show();	
				ButtonCustomerService.show();
				ButtonSmartPurse.show();
				ButtonUpdateCustomer.show();
				// Set enable botton
				//$("#btnAddProduct").button( "enable" );
			
				//close
			 	$( "#dialog-form" ).dialog( "close" );	
				
				// IF customer has remain credit sale amount show popup
				var params = {'m':'chkRm','custid':custID};
				$.ajax({
						type: 'POST',
						cache: false,
						url: url,
						data: params,
						success: function(data){
							var obj= eval('('+data+')');
							var flag = 0;
							alert(data);
							$("#customerServiceName").attr('innerHTML',custName);
							
							if (obj['remain']!='0')
							{
								$("#spInfo").attr('innerHTML','ลูกค้ามียอดค้างชำระทั้งสิ้น จำนวน<font color=red> '+ obj['remain']+ ' </font>  บาท');
								flag = 1;
							}

							if (obj['sCnt']!='0'){
								
								$('#tbCourse').show();
								$( "#tbCourse tbody tr" ).remove();
								//Insert data to first row.
								$( "#tbCourse tbody:first" ).prepend( obj['data'] ); 
								$( "#dialog-alert" ).dialog( "option", "height", 350);
								flag = 1;

							}else{
								$('#tbCourse').hide();
								$( "#dialog-alert" ).dialog( "option", "height", 170);
							}
							
							if (flag==1)
							{
								$( "#dialog-alert" ).dialog({'title':"Information"});
								$( "#dialog-alert" ).dialog( "open" );
								$( "#dialog-alert" ).dialog( "option","buttons",{
									"Close":function(){$( this ).dialog( "close" );}
								});
							}
						}
				});
		});
 
		function AddProduct(){
			var row = $("#rowCount").attr('innerHTML');
			var ds = {'proID':cboProductList.val(),'m':'s_prod','type':cboProductType.val(),'amt':$("#Amount").val()};
			$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: ds,
					success: function(data){
					//alert(data);
						var m=eval("("+data+")");
					
							if (row=="0"){
									//Remove row info
									$( "#resultData tbody tr" ).eq(0).remove();
							}
						 
							var price = new Number(m["Price"]);
							var total = parseFloat($("#Amount").val()) * parseFloat(m["Price"]);
							var c_total = new Number(total);
							var rowCount= new Number(parseInt(row)+ 1);
							var $html="";
							
							o_product_list[cboProductList.val()]=$("#Amount").val();
							// iAmount = iAmount+total;
							// iTotalNet= iAmount-iDiscount;
							
							if ((rowCount%2)!= 0)
								$html="<tr class=row1>";
							else 
								$html="<tr>";
								
							 $html +="<td align='right'>"+ rowCount.toFixed() +"</td>";
							 $html +="<td style='display:none'>"+m["ID"]+"</td>";
							 $html +="<td style='display:none'>"+m["Type"]+"</td>";
							 $html +="<td align='left' style='word-wrap: break-word;'>"+m["ProductName"]+"</td>";
							 $html +="<td align='left' style='word-wrap: break-word;'>"+m["CatName"]+"</td>";
							 $html +="<td align='center'>"+m["TypeName"]+"</td>";
							// $html +="<td align='right'>"+$("#Amount").val()+"</td>";
							 $html +="<td align='right'><input type='textbox' style='text-align:right;font-size:11px;border:1px solid #ccc;padding-top:3px;padding-bottom:3px;' name='txtamt'  maxlength='4' size='4'  value='"+$("#Amount").val()+"'/></td>";
							 $html +="<td align='center'>"+m["Unit"]+"</td>";
							 $html +="<td align='right'>"+ CommaFormatted(price.toFixed(2))+"</td>";
							 $html +="<td align='right'>"+ CommaFormatted(c_total.toFixed(2))+"</td>";
							 $html +="<td align='center' style='color:red'>0</td>";	
							 $html +="<td align='right' style='color:blue'>"+ CommaFormatted(c_total.toFixed(2))+"</td>";						 
							 $html +="<td align='center'><img src='./images/discount.png' class='btnDiscount' style='cursor:pointer'  title='Discount' border='0'/></td>";
							 $html +="<td align='center'><img src='./images/remove.png' class='btnDel' style='cursor:pointer'  title='Delete this row' border='0'/></td>";
							 $html +="<td style='display:none'>0</td>";						 
							 $html +="<td style='display:none'>"+m["Times"]+"</td>";		
							 $html +="</tr>";
							//Insert data to first row.
							 $( "#resultData tbody:first" ).append($html); 
							
							//set rows count
							$("#rowCount").attr('innerHTML',rowCount);
							
							//Set summary total
							SummaryAmount(true);
						 	//Can input payment amount
							$("#txtPayAmt").attr('readonly',false);
					}
				});
		}
		$("#btnAddProduct").click(function(){
			var list=[];
			if ( $("#Amount").val()=="" ||  $("#Amount").val()=="0") {
				$("#Amount").addClass("ui-state-error");
				return false;
			}else{
				$("#Amount").removeClass("ui-state-error");
			}
			
			//if (o_product_list[cboProductList.val()]) {
			//	alert(cboProductList.children( ":selected" ).text()+ ' already exist!!');
			//	return false;
			//} 
			
			$( "#resultData tbody tr" ).each(function(){
				// Product ID 
				var pdid = $(this).find("td").eq(1).html();    
				// Type ID
				var tid = $(this).find("td").eq(2).html();    
				// Amount
				var amt = $(this).find("input[name=txtamt]").val(); 

				list.push({'pid':pdid,'amt':amt,'type':tid});
			});
			list.push({'pid':cboProductList.val(),'amt':$("#Amount").val(),	'type':cboProductType.val()	});

			$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'list':list,'m':'checkstock'},
					success: function(data){
						var obj=eval('('+data+')');
						 if (obj['result']=='0'){
							 alert( 'The product : "' + obj['ProductName'] + '" is not enough.');// ('+obj['Amount'] + ' ' + obj['Unit']+')' );
							return false;						
						 }else{
							AddProduct();
							return true;
						 }
					}
			});
			return false;
		});
		$("input[name=txtamt]").live('blur',function() { 
			var iamt = $(this).val();
			if (iamt==''){
				alert('Please input amount.');
				$(this).focus().select(); 
			}
		});
		$("input[name=txtamt]").live('keyup',function(event){
			
			var iamt = $(this).val();

			rowSelect = $(this).parent().parent();
			//Get Price
			var iprice= new Number(rowSelect.find("td").eq(8).html().replace(',','').replace(',',''));
			//Get Discount AMt
			var idiscount= new Number(rowSelect.find("td").eq(14).html().replace(',','').replace(',',''));
	 
			// Summary
			var itotal= new Number((parseFloat(iprice) * parseFloat(iamt)));
			var itotalNet = new Number((parseFloat(iprice) * parseFloat(iamt)) - parseFloat(idiscount));
			rowSelect.find("td").eq(9).html( CommaFormatted( itotal.toFixed(2) ));
			rowSelect.find("td").eq(11).html( CommaFormatted( itotalNet.toFixed(2) ));
			SummaryAmount(true);
			
			calculateRemainAmt($("#txtPayAmt").val());
		});
		$("input[name=txtamt]").live('keypress',function(e){
			
			if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=46){
				return false;
			}
		});
		
		//buton extra discount 
		$(".btnExDiscount").live('click',function(){
			openDialogSpecail();
			return false;
		});
		function countArray(obj) {
		  var prop;
		  var propCount = 0;

		  for (prop in obj) {
			propCount++;
		  }
		  return propCount;
		}
		
		function openDialogSpecail(){
			$("#dialog-special").dialog("open");
			$("#dialog-special").dialog("option","buttons",	{
				"OK":function(){
					if (countArray(objSelectDiscount)==0){
						objSelectDiscount=objExDiscount[0];
						//alert(objSelectDiscount['Type']);
					}
					 //tyep: 2=Cash , 1: Premium
					if (objSelectDiscount['Type']=='2'){
						 //Cash
						 // isClick=true;
						 var iDiscount=0;
						 var special = new Number(objSelectDiscount['Discount'].replace(',','').replace(',',''));
						 var iamt= new Number($("#iAmount").attr('innerHTML').replace(',','').replace(',',''));
						 $( "#resultData tbody tr").each(function(){
							// Col Discount
							iDiscount += convertToNumber($(this).find("td").eq(14).html());
						});
						 var inet= new Number($("#iTotalNet").attr('innerHTML').replace(',','').replace(',',''));			
						 iDiscount= iDiscount+special;
						 inet= iamt - iDiscount;
						 $("#iDiscount").attr('innerHTML', CommaFormatted(iDiscount.toFixed(2)));
						 $("#iTotalNet").attr('innerHTML', CommaFormatted(inet.toFixed(2)));
						 $("#txtRemainAmt").val(CommaFormatted(inet.toFixed(2))).change();
				 
					}else{
						var iDiscount=0;
						 var iamt= new Number($("#iAmount").attr('innerHTML').replace(',','').replace(',',''));
						$( "#resultData tbody tr").each(function(){
							// Col Discount
							iDiscount += convertToNumber($(this).find("td").eq(14).html());
						});
						 inet= iamt - iDiscount;
						 $("#iDiscount").attr('innerHTML', CommaFormatted(iDiscount.toFixed(2)));
						 $("#iTotalNet").attr('innerHTML', CommaFormatted(inet.toFixed(2)));
						 $("#txtRemainAmt").val(CommaFormatted(inet.toFixed(2))).change();
					
					}
					alert(objSelectDiscount['Desc']);
				 	$( this ).dialog( "close" );
				},
				"Cancel":function(){
					$( this ).dialog( "close" );
				}
			});
		}
 
		
		//button Delete
		$(".btnDel").live('click',function(){
				rowSelect = $(this).parent().parent();
				ID= rowSelect.find("td").eq(1).html();//get productid
				delete o_product_list[ID];

				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						rowSelect.remove(); // remove row
						//Remove number
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						// Re-Calculate summary
						SummaryAmount(true);
						 
						var iRow=1;
						//load for re run No.
						$( "#resultData tbody tr").each(function(){
							if ($(this).find("td").eq(0).html() !="Amount :")
								 $(this).find("td").eq(0).html(iRow); 
								
							iRow++;
						});
						$( this ).dialog( "close" );
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
				return false;
		});
		
		// Button Add Customer 
		$("#btnAddCust").click(function (){
			$.post("a_customer.php",  {'m':'runningCode'} , function(data){
				//alert(data);
				$("#Code").val(data);
			});	
			var d = new Date();

			var curr_date = d.getDate();

			var curr_month = d.getMonth() + 1;
			 
			var curr_year = d.getFullYear();	
			
			$("#CreatedDate").val(curr_date + "/" + curr_month + "/" + curr_year);			
			$("#dialog-AddCust").dialog({'title':"Create new Customer"});
			$("#dialog-AddCust" ).dialog( "open" );
			$( "#dialog-AddCust" ).dialog( "option","buttons",{
				"Create":function(){

					addCustFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
					 
						var o = {};
						o["Code"]=Code.val();
						o["FirstName"]=FirstName.val();
						o["LastName"]=LastName.val();
						o["BirthDay"]=Birthday.val();
						o["Address"]=Address.val();
						o["Telephone"]=Telephone.val();
						o["Email"]=Email.val();
						o["CardID"]=$("#CardID").val();
						o['Sex']=$('input[name=Sex]:checked').val();
						
						$.ajax({
							type: 'POST',
							cache: false,
							url: 'a_customer.php',
							data:{"m":"main_addcust","var":o},
							success: function(data){
								var ar=eval("("+data+")");
								// ar["ID"] --> CustID
								//Fixed
								m_CustomerID = ar["ID"];
								$("#custid").val(ar["ID"]);
								//>>
								main_custcode.val(ar["Code"]);
								main_custname.val(ar["FirstName"] + " " + ar["LastName"]);

								ButtonCustomerHistory.show();	
								ButtonCustomerService.show();
								ButtonSmartPurse.show();
								ButtonUpdateCustomer.show();
							},
							error:function(){
								//
							},
							complete:function(){
								$( "#dialog-AddCust" ).dialog( "close" );
							}
						});
						
						
					}
					return false;
				},
				"Cancel":function(){$( this ).dialog( "close" );}
			});
		});

		
		//******************
		// Button Discount Product
		//******************
		$(".btnDiscount").live('click',function(){
			//Add new
			$("#frmLogin").hide();	
			$("#frmSelectDiscount").show();
			$("input:radio[id='type_1']").attr('checked',true);
			$("#iDiscount1").attr('innerHTML', $("#userDiscount").val());
			$("#spDiscount").show();
			$("#spCard").hide();
			$("#spGiftVoucher").hide();
			$( "#dialog-Login" ).dialog( "option", "height",360 );			
			
			rowSelect = $(this).parent().parent();
			ID=$(this).parent().parent().find("td").eq(1).html();
			
			
			$("#dialog-Login").dialog({'title':"Discount"});
			$("#dialog-Login" ).dialog( "open" );
			$( "#dialog-Login" ).dialog( "option","buttons",{
				"Ok":function(){
					if (modeLogin=="login"){
						if (checkUserLogin() ==true){
								//Show Wating
							$("#wating").fadeIn(200).show();
							$.post(url ,{'m':'checkuser' , 'uname':$("#username").val() 	,'pwd':$("#password").val()}, function(data){
							//Show Wating
								$("#wating").fadeOut(200).hide();
								//Remove not used
								if (eval("("+data+")")==1){
									$("#frmLogin").fadeOut('200').hide();	
									$("#frmSelectDiscount").fadeIn('500').show();	
									$("input:radio[id='type_1']").attr('checked',true);
									$("#iDiscount1").attr('innerHTML', $("#userDiscount").val());
									$("#spDiscount").show();
									$("#spCard").hide();
									$( "#dialog-Login" ).dialog( "option", "height",360 );
									modeLogin="discount";
								}else{
									$(".validateTipsCust")
										.text( "Username or password incorrect!!" )
										.addClass( "ui-state-highlight" );
									setTimeout(function() {
										$(".validateTipsCust").removeClass( "ui-state-highlight", 1500 );
									}, 500 );
								}
							});
						}
					}else{
						//Check user select discount type
						$("#frmLogin").hide();	
						$("#frmSelectDiscount").show();
						var chk_type=$("input:radio[name='discounttype']:checked").val();
						var disamt=0;
						var type='';
						//Total Column
						var iTotal= rowSelect.find("td").eq(9).html().replace(',','').replace(',','');						 
						var net=0;
						
						if (chk_type==1){ 
							// Discount by user
							disamt = $("#iDiscount1").attr('innerHTML').replace(',','').replace(',','') ;
							//type=' %';
							rowSelect.find("td").eq(10).html( disamt + '  %' );
							disamt = parseFloat(iTotal) * parseFloat(disamt) / 100;
						}else if (chk_type==3){
							if ($("#giftAmt").val() =="")
								disamt=0;
							else
								disamt = $("#giftAmt").val().replace(',','').replace(',','') ;
								
							rowSelect.find("td").eq(10).html( disamt );
						}else{ 
							// Discount by Card Coupon
							type=$("#iDiscount2_type").attr('innerHTML') ;
							disamt = $("#iDiscount2").attr('innerHTML').replace(',','') ;
							rowSelect.find("td").eq(10).html( disamt + '  ' + type );
						
							if (type!="Bath"){
								disamt = parseFloat(iTotal) * parseFloat(disamt) / 100 ;
							}	
						}
						//total - discount
						net = new Number(parseFloat(iTotal) - Math.ceil(disamt) );
						 
						if (net<0){
							rowSelect.find("td").eq(10).html( 0 );
							alert('Discount more than total amount');
							return;
						}
						rowSelect.find("td").eq(11).html( CommaFormatted( net.toFixed(2) ));
						rowSelect.find("td").eq(14).html(Math.ceil(disamt));						
						
						SummaryAmount(true);
						$("#txtPayAmt").val(0);
						
						$( this ).dialog( "close" );
					}
				},
				"Cancel":function(){
					$( this ).dialog( "close" );
				}
			});	
			return false;			
		});
		
		function SummaryAmount(type){
			//loop for summary
			var iTotal=0;
			var iDiscount=0;
			var iNet=0;
			objExDiscount=[];
			objSelectDiscount=[];
			isClick=false;
		 
			$( "#resultData tbody tr").each(function(){
			// Col Total Amt
				iTotal += convertToNumber($(this).find("td").eq(9).html());
				// Col Discount
				iDiscount += convertToNumber($(this).find("td").eq(14).html());
				//Total Net
				iNet += convertToNumber($(this).find("td").eq(11).html());
			});
			
			$("#iAmount").attr('innerHTML',CommaFormatted(iTotal.toFixed(2)));
			$("#iDiscount").attr('innerHTML',CommaFormatted(iDiscount.toFixed(2)));
			$("#iTotalNet").attr('innerHTML',CommaFormatted(iNet.toFixed(2)));				
			$("#txtRemainAmt").val(CommaFormatted(iNet.toFixed(2))).change();
			 
			if (type==true){
			 
				var showEx=false;
				$.each(m_discount, function(key, value) {
					if (parseFloat(iNet) >= parseFloat(key)) {
						showEx=true;
						objExDiscount.push(value);
					}
				});

	 			if (showEx){
					$(".extra").show().fadeIn('500');
					var i=0;
					var str="";
					var check='checked';
					$.each(objExDiscount, function() {
						if (i!=0){
							check='';
						}else{
							//objSelectDiscount=$(this);
						}
						str +="<input type='radio' name=\'specialdis\' id=\'dis_"+i+"\' "+check+" value=\'"+ i +"\' />" + objExDiscount[i]['Desc'] +"<br>";
						i++;
					});
					$("#discountInform").attr('innerHTML',str );
					//openDialogSpecail();
					
				}
				else {
					$(".extra").hide('slow');
					objExDiscount=[];
					objSelectDiscount=[];
				}
				
				if (countArray(objSelectDiscount)!=0){
					if (objSelectDiscount['Type']=='2'){
						var specialamt=objSelectDiscount['Discount'].replace(',','').replace(',','');
						iTotal=$("#iAmount").attr('innerHTML').replace(',','').replace(',','');
						iDiscount=$("#iDiscount").attr('innerHTML').replace(',','').replace(',','');
						iDiscount+=specialamt;
						iNet=iTotal-iDiscount;
						$("#iAmount").attr('innerHTML',CommaFormatted(iTotal.toFixed(2)));
						$("#iDiscount").attr('innerHTML',CommaFormatted(iDiscount.toFixed(2)));
						$("#iTotalNet").attr('innerHTML',CommaFormatted(iNet.toFixed(2)));				
						$("#txtRemainAmt").val(CommaFormatted(iNet.toFixed(2))).change();
					}
				}
			}
		}
		$("input:radio[name:specialdis]").live('click',function(){
			if ($(this).attr('name')=='specialdis')
				objSelectDiscount=objExDiscount[$(this).val()];
			//alert(objSelectDiscount['Desc']);
		});
		function convertToNumber(num){
			var value=0;
			num=num.replace(',','');
			if (!(isNaN(num))){
				value= parseFloat( num , 10);
			}
			return value;
		}
		ButtonCancelBill.click(function(){
			$("#Act").attr("action", "cancelbill.php");
			$('#Act').submit();
		});
	
		//******************
		// Button Customer History
		//******************
		ButtonCustomerHistory.live('click',function(){
			$("#Act").attr("action", "customer_history.php");
			$('#Act').submit();
		});

		//******************
		// Button Credit Sale 
		//******************
		$("#btnCreditsale").live('click',function(){
			$("#Act").attr("action", "creditSale.php");
			$('#Act').submit();
		});
 
				
		ButtonCustomerService.click(function(){
			$("#Act").attr("action", "customer_service.php");
			$('#Act').submit();
		});
		
		ButtonSmartPurse.click(function(){
		 		$("#dialog-smartpurse").dialog({'title':'Smart Purse'});
				$("#dialog-smartpurse" ).dialog( "open" );
				$( "#dialog-smartpurse" ).dialog( "option","buttons",{
					"Cancel":function(){
						ID="";
						$( this ).dialog( "close" );
						}
				});
		});

		ButtonUpdateCustomer.click(function(){
			var dataSet={'id':m_CustomerID,'m':'detail'};  
			 
			 $.ajax({
				type: 'POST',
				cache: false,
				url: 'a_customer.php',
				data: dataSet,
				success: function(data){
					var obj=eval('('+data+')');
				  	for (value in obj){
						//alert(value);
						txt="#"+value;
					
						if (value=="BirthDay"){
							//alert(obj[value]);
							$("#Birthday").datepicker("setDate" , obj[value]) ;
						}else if (value=="Sex"){
							if (obj[value]=="1") //Male
								$("#Sex_2").attr('checked','checked');
							else	//Female
								$("#Sex_1").attr('checked','checked');
								
						}else{
							$(txt).val(obj[value]);
						}
					}
				}
			});
			
			$("#dialog-AddCust").dialog({'title':"Update Customer"});
			$("#dialog-AddCust").dialog("open");
			$("#dialog-AddCust").dialog( "option","buttons",{
				"Update":function(){
					addCustFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
					 
						var o = {};
						o["Code"]=Code.val();
						o["FirstName"]=FirstName.val();
						o["LastName"]=LastName.val();
						o["BirthDay"]=Birthday.val();
						o["Address"]=Address.val();
						o["Telephone"]=Telephone.val();
						o["Email"]=Email.val();
						o["CardID"]=$("#CardID").val();
						o['Sex']=$('input[name=Sex]:checked').val();
						
						$.ajax({
							type: 'POST',
							cache: false,
							url: 'a_customer.php',
							data:{"m":"main_editcust","var":o,"id":m_CustomerID},
							success: function(data){
								var ar=eval("("+data+")");
								//Fixed
								m_CustomerID = ar["ID"];
								$("#custid").val(ar["ID"]);
								//>>
								main_custcode.val(ar["Code"]);
								main_custname.val(ar["FirstName"] + " " + ar["LastName"]);
								
							},
							error:function(){
								//
							},
							complete:function(){
								$( "#dialog-AddCust" ).dialog( "close" );
							}
						});
						
					}
					return false;
				}
				,"Cancel":function(){
					$( this ).dialog( "close" );
				}
			}
			);
		});
		
		// On Click Amount 
		$("#txtPayAmt").click(function() {
			$(this).focus().select(); 
		} );
		
		//On keypress
		$("#txtPayAmt").keyup(function(event){
			calculateRemainAmt($(this).val());

		});
		
		function calculateRemainAmt(payAmt){
			var iInputPay=payAmt;
				
			if (isNaN(iInputPay) || iInputPay=="")
				iInputPay=0;
			
			//alert((iInputPay));
			var m_remain=parseFloat($("#iTotalNet").attr('innerHTML').replace(',','').replace(',','')) - parseFloat(iInputPay);
			if (isNaN(m_remain)){
				m_remain=0;
			 }
			if(m_remain<0){
				$("#txtChangeAmt").val(m_remain * (-1));
				m_remain=0;
			
			}else{
				$("#txtChangeAmt").val(0);
			}
				
			$("#txtRemainAmt").val(m_remain).change();
		}
		
		//Eventy Text Payment 2 Keyup 
		$("#txtPayAmt2").keyup(function(event){
		
			var iInputPay=$(this).val();
				
			if (isNaN(iInputPay) || iInputPay=="")
				iInputPay=0;
			
			//alert((iInputPay));
			var m_remain=parseFloat($("#txtRemainAmt").val().replace(',','').replace(',','')) - parseFloat(iInputPay);
			
			if(m_remain<0){
				$("#txtChangeAmt2").val(m_remain * (-1));
				m_remain=0;
			
			}else{
				$("#txtChangeAmt2").val(0);
			}
				
			$("#txtRemainAmt2").val(m_remain).change();
		});
		
		//*************** Save Data ****************************//
		function checkDataForSave(){
			var allVars=[];
			arPay=[],
			custid=0,
			payType=$("input:radio[name='PayType']:checked").val(),
			payType2=0,
			cardNo="",
			cardNo2="",
			IsCredit=0,
			ExID=0,
			IsExtraDiscount=0,
			tDiscount = $("#iDiscount").attr('innerHTML').replace(',','').replace(',',''),
			tAmount = $("#iAmount").attr('innerHTML').replace(',','').replace(',',''),
			tTotalAmount = $("#iTotalNet").attr('innerHTML').replace(',','').replace(',',''),
			isOtherPay=$("#IspayOther").attr('checked');
		
			//payment
			var m_pay = $("#txtPayAmt").val().replace(',','').replace(',','');
			var m_change = $("#txtChangeAmt").val().replace(',','').replace(',','');
			var m_remain = $("#txtRemainAmt").val().replace(',','').replace(',','');

			var m_pay2=0;					
			var m_remain2=0;
			
			var tPay=0;		

			if (isOtherPay){
				m_pay2 =$("#txtPayAmt2").val().replace(',','').replace(',','');
				payType2 = $("input:radio[name='PayType2']:checked").val();
				
				if ((payType2==2) ||(payType2==3))
					cardNo2 = $("#txtCardNo2").val();
					
				IsCredit=0;
				
				tPay= parseFloat(m_pay) + parseFloat(m_pay2);
				
				if (parseFloat(tTotalAmount) < parseFloat(tPay)){
					m_pay2 = parseFloat(tTotalAmount) - parseFloat(m_pay);
					tPay= parseFloat(m_pay) + parseFloat(m_pay2);
				}
				arPay.push({
					'PaymentType':payType2,					
					'CardNo':cardNo2,
					'PaymentAmount':m_pay2
				});
			}else{
				
				if (parseFloat(tTotalAmount) < parseFloat(m_pay)){
					m_pay =	parseFloat(tTotalAmount); 
				}
				
				tPay = parseFloat(m_pay);
				
				IsCredit= parseFloat( m_remain ) > 0?1:0;	
			}
			
			
			// 1: member , 2:non member
			custid = $("input:radio[name='CustType']:checked").val();
			if  ($("input:radio[name='CustType']:checked").val()==1) {
				//custid = m_CustomerID;
				//custid=$("#custid").val();
			}
						
			if ((payType==2) ||(payType==3)){
				cardNo=$("#txtCardNo").val();
			}  
			 
			if (countArray(objSelectDiscount) !=0){
				//1:Premium , 2:Cash;
				IsExtraDiscount=objSelectDiscount['Type'];
				ExID=objSelectDiscount['ID'];
			}
			
			allVars.push({'CustID':custid,
						'productlist':getProductList(),
						'Amount': tAmount,
						'Discount': tDiscount,
						'PaymentAmount': tPay,
						'TotalNet': tTotalAmount, 
						'RemainAmount': parseFloat(tTotalAmount) - parseFloat(tPay),
						'IsCreditSale': IsCredit,
						'ExID': ExID,
						'IsExtraDiscount':IsExtraDiscount
						});
						
			arPay.push({
						'PaymentType':payType,					
						'CardNo':cardNo,
						'PaymentAmount':m_pay
						});
						
			$.ajax({
				type: 'POST',
				cache: false,
				url: 'a_main.php',
				data:{'m':'add','v':allVars,'p':arPay},
				success: function(data){
					 //alert(data);
					var obj= eval('('+data+')');
					alert(obj['info']);
					newwindow=window.open('pos_print.php?i='+obj['id'],'_blank','height=450px,width=350px');
					if (window.focus) {newwindow.focus();}	 
					
					clearData();
				},
				error:function(){
					//
					alert('!!Error, please contact administrator.');
				},
				complete:function(){
					o_product_list={};
					objExDiscount=[];
					objSelectDiscount=[];
					$( "#dialog-AddCust" ).dialog( "close" );
				}
			});
		}
		
		//Save data
		$(".Save").click(function(){
			var iDiscount=0;
			if (checkBeforeSave()){	
				$( "#resultData tbody tr").each(function(){
							// Col Discount
						iDiscount += convertToNumber($(this).find("td").eq(14).html());
				});	
				// Don't show login screen
				//if (iDiscount<=0){
					checkDataForSave();
					//return;
				//}
				 
				/*$("#frmLogin").show();	
				$("#frmSelectDiscount").hide();
				$( "#dialog-Login" ).dialog( "option", "height",270 );				
				$("#dialog-Login").dialog({'title':"Login."});
				$("#dialog-Login" ).dialog( "open" );
				$( "#dialog-Login" ).dialog( "option","buttons",{
					"Ok":function(){
						if (checkUserLogin() ==true){
								//Show Wating
							$("#wating").fadeIn(200).show();
							$.post(url ,{'m':'checkuser' , 'uname':$("#username").val() 	,'pwd':$("#password").val()}, function(data){
								$( "#dialog-Login" ).dialog( "close" );
								$("#wating").fadeOut(200).hide();
								if (eval("("+data+")")==1){ 
									checkDataForSave();
								}else{
									$(".validateTipsCust")
										.text( "Username or password incorrect!!" )
										.addClass( "ui-state-highlight" );
									setTimeout(function() {
										$(".validateTipsCust").removeClass( "ui-state-highlight", 1500 );
									}, 500 );
								 
								}	
							});
						}
					},
					"Cancel":function(){
						$( this ).dialog( "close" );
					}
				});	*/	
			}
		});
		
 
		//Print data
		$(".Print").click(function(){
			newwindow=window.open($(this).attr('href'),'_blank','height=500,width=350');
			if (window.focus) {newwindow.focus();}
			return false;
		});
		//Clear data
		$(".Abort").click(function(){

			  clearData();
			 return false;
 			 			 
		});
		//>>>> End Event Handler

	  	//*********************************
		// Method & Function
		//*********************************
		function checkUserLogin(){
			var bValid=true;
 
			if (!(checkInputFile($("#username")))){
				$("#username").addClass( "ui-state-error" );
				bValid  = bValid && false;
			}else{
				$("#username").removeClass( "ui-state-error" );
				bValid  = bValid && true;
			}
				
			if (!(checkInputFile($("#password")))){
				$("#password").addClass( "ui-state-error" );
				bValid  = bValid && false;
			}else{
				$("#password").removeClass( "ui-state-error" );
				bValid  = bValid && true;	
			}

			return bValid;
		}
		
		function getProductList(){
			var list=[];
			
				$( "#resultData tbody tr" ).each(function(){
					// Product ID 
					var pdid = $(this).find("td").eq(1).html();    
					// Type ID
					var tid = $(this).find("td").eq(2).html();    
					// Amount
					var amt = $(this).find("input[name=txtamt]").val();    
					// Price
					var price = $(this).find("td").eq(8).html().replace(',','');    				
					// TOtal
					var total = $(this).find("td").eq(9).html().replace(',','');    
					// Discount
					var discount = $(this).find("td").eq(14).html().replace(',','');    		
					
					var times = $(this).find("td").eq(15).html().replace(',','');    		
					
					list.push({'Product':pdid,
									'Amount':amt,
									'Price':price,
									'Total':total,
									'Type':tid,
									'Discount':discount,
									'Times':times
								});
				});
				
				return list;
			 
		}
		//Clear data
		function clearData(){
			$( "#resultData tbody tr" ).remove(); 
			$( "#txtPayAmt, #txtRemainAmt" ).val('0').attr('readonly',true);
			$( "#txtPayAmt2, #txtRemainAmt2" ).val('0').attr('readonly',true);
			$("#txtCardNo , #Amount").val('');
			$("#txtCardNo2 , #Amount2").val('');
			$("#iAmount , #iDiscount , #iTotalNet ,#rowCount").attr('innerHTML','0');
			$(".extra").show().hide();
			main_custcode.val('');
			main_custname.val('');		
			m_CustomerID=0;
			$("#CustCode").val('');
			$("#CustName").val('');
			$("#custid").val('');
			ButtonCustomerHistory.hide();	
			ButtonCustomerService.hide();	
			ButtonSmartPurse.hide();
			ButtonUpdateCustomer.hide();
			$("#IspayOther").attr('disabled','disabled');
			$("#IspayOther").removeAttr('checked');
			$(".pay2").fadeOut('slow');		
			o_product_list=[];
		//Insert data to first row.
		 $( "#resultData tbody:first" ).append("<tr><td colspan='16' align='center'><img src='images/info1.png' border='0'/></td></tr>"); 
		}
		
		//get data
		function loadDataToControls(){
			 
			//main_custcode.val('');
			//main_custname.val('');	
			if (main_custcode.val()!=""){
				ButtonCustomerHistory.show();	
				ButtonCustomerService.show();
				ButtonSmartPurse.show();
				ButtonUpdateCustomer.show();
			}
			$(".pay2").hide();
			//hide discount
			$(".extra").hide();	
			
			// Set icon
			// Search button on main screen
			$("#btnAddProduct").button({
				icons:{
				 primary: "ui-icon-circle-plus"
				}
			});	
			$("#btnSmart").button({
				icons:{
				 primary: "ui-icon-circle-plus"
				}
			});				
	 
			//Set autocompleted combo
			cboProductList.combobox();
			// Search button on dialog
			$("#btndlgSearch").button({
				icons:{
					primary:"ui-icon-circle-zoomout"
				}
			});
			//Set Input only numeric
			$("#Amount,#txtPayAmt,#txtPayAmt2,#txtChangeAmt,#txtChangeAmt2").numeric();
			//Set Readonly
			$("#txtPayAmt").attr('readonly',true);
			//$("#txtChangeAmt").attr('readonly'true);
			$("#txtRemainAmt,#txtRemainAmt2,#txtChangeAmt,#txtChangeAmt2").attr('readonly',true);
		
			$.get(url, {"c":"cc"},function(data){
				 var obj=eval('('+data+')');
				 if (obj!=null) {
					$.each(obj, function(index, text) {
						$("#cboCardType").prepend(
							$('<option></option>').val(index).html(text)
						 );
					});
				}
			});		
			$("#cboCardType").append($('<option></option>').val(-1).html('---Select ---'));

		 
			
			//Load Product Type
			$.get(url, {"c":"t"},function(data){
				//alert(data);
				var obj=eval('('+data+')');
				if (obj!=null){
					$.each(obj, function(index, text) {
							
						cboProductType.append(
						$('<option></option>').val(index).html(text)
						 );
					});
				}
			});	
			
			//Load Product List
			//alert(url+"?c=rp");
 
			$.get(url, {"c":"rp"},function(data){
				 //alert(data);
				 var obj=eval('('+data+')');
				 
				if (obj!=null){
		 
					$.each(obj, function(index, text) {
						 
						cboProductList.append(
							$('<option></option>').val(text).html(index)
						 );
					});
				}
			});		
			// load discount
			$.post(url,{"m":"check_ex_discount"},function(data){
				//	 alert(data);
					var m;
					var promotion="";
					//alert(data);
					var obj=eval('('+data+')');
					if (obj!=null){
					//m_discount[
						var	i=1;
						for (value in obj){
							m = obj[value];
							m_discount[m["Amount"]]={'Discount':m["Discount"]
													,'Type':m["Type"] 
													,'Desc':m["Description"]
													,'ID':m["ID"]
													,'Amount':m["Amount"]
													};
							if (i!=1)
								promotion += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
								
							promotion += m["Description"];
							i++;
						}
						
						 $(".promotion").find('p').attr('innerHTML' , promotion);
					}
			});
			
			$("#SmartAmount").keypress(function(e){
		
				if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
					return false;
				}
			});
		}
	
		function checkBeforeSave(){
			var bValid=true;
			var payAmount=0;
			var payAmount2=0;
			var Total=0;
			var vPayType;
			var vPayType2;
			var custType=$("input:radio[name='CustType']:checked").val();
			var isOtherPay=$("#IspayOther").attr('checked');
			var rowsTable=$("#rowCount").attr('innerHTML');
			var iRows= parseInt(rowsTable,10);
			//alert(iRows);
			//1:member , 2:non-member
			if (custType=='1') {
				bValid = bValid & checkInputValue(main_custcode );
				bValid = bValid & checkInputValue(main_custname);
			
				// case other pay -> toal pay - total must be zero 
				if (isOtherPay){
					payAmount=$("#txtPayAmt").val();
					Total=$("#iTotalNet").attr('innerHTML').replace(',','');
					payAmount2=$("#txtPayAmt2").val();
					
					if (isNaN(payAmount))
						payAmount=0;
						
					//Select Other pay but not input payment in other pay display error
					if (isNaN(payAmount2)){
						bValid = bValid & false;
						payAmount2=0;
						$("#txtPayAmt2").addClass( "ui-state-error" );
						return bValid;
					}
							
					
					if ( (parseFloat(payAmount) + parseFloat(payAmount2)) < parseFloat(Total)){
						bValid = bValid & false;
						$("#txtPayAmt").addClass( "ui-state-error" );
						$("#txtPayAmt2").addClass( "ui-state-error" );
					}else {
						bValid = bValid & true;
						$("#txtPayAmt").removeClass('ui-state-error');
						$("#txtPayAmt2").removeClass('ui-state-error');
					}						
					if (iRows==0){
						alert('ไม่สามารถบันทึกข้อมูลได้');
						bValid = bValid & false;
						return ;
					}
				}
				
				
			}else{
				//Main Payment
				if (iRows==0){
						alert('ไม่สามารถบันทึกข้อมูลได้');
						bValid = bValid & false;
						return;
				}
				payAmount=$("#txtPayAmt").val();
				
				Total=$("#iTotalNet").attr('innerHTML').replace(',','');

				//Main Payment
				if (isNaN(payAmount))
					payAmount=0;
					
					

				$("#resultData tbody tr").each(function(){
					// Product ID 
					var type = $(this).find("td").eq(5).html();    
					if (type=='Course'){
						alert('Non-member cannot buy Course.');
						bValid = bValid & false;
						return;
					}
 				});
							
				//Other Pay
				if (isOtherPay){
					payAmount2=$("#txtPayAmt2").val();
					if (isNaN(payAmount2))
						payAmount2=0;
						
					if ( (parseFloat(payAmount) + parseFloat(payAmount2)) < parseFloat(Total)){
						bValid = bValid & false;
						$("#txtPayAmt").addClass( "ui-state-error" );
						$("#txtPayAmt2").addClass( "ui-state-error" );
					}else {
						bValid = bValid & true;
						$("#txtPayAmt").removeClass('ui-state-error');
						$("#txtPayAmt2").removeClass('ui-state-error');
					}
				}else{
					if (parseFloat(payAmount) < parseFloat(Total)){
						bValid = bValid & false;
						$("#txtPayAmt").addClass( "ui-state-error" );
					}else {
						bValid = bValid & true;
						$("#txtPayAmt").removeClass('ui-state-error');
					}
				}
			}
			
			//1:cash, 2:CreditCard, 3:Smart Purse
			vPayType=$("input:radio[name='PayType']:checked").val();
			
			if ((vPayType==2) || (vPayType==3)){
				bValid = bValid & checkInputValue( $("#txtCardNo" ) );				
			}
			
			if (isOtherPay){
				vPayType2=$("input:radio[name='PayType2']:checked").val();
							
				if ((vPayType2==2) || (vPayType2==3)){
					bValid = bValid & checkInputValue( $("#txtCardNo2" ) );				
				}
			}
			 
			return bValid;
		}
		 
		function checkInputControl(){
			if (!(checkInputFile(dlg_custCode) || checkInputFile(dlg_custName) || checkInputFile(dlg_custCardId))){
				dlg_custCode.addClass( "ui-state-error" );
				dlg_custName.addClass( "ui-state-error" );
				dlg_custCardId.addClass( "ui-state-error" );
				updateTips( "Please input at least one condition");
				return false;
			}else{
				dlg_custCode.removeClass( "ui-state-error" );
				dlg_custName.removeClass( "ui-state-error" );
				dlg_custCardId.removeClass("ui-state-error" );
				return true;
			}
		}
		// Check Input Files
		function checkInputFile( o ) {
			if (o.val().length < 1 ) {
				return false;
			} else {
				return true;
			}
		}			
	
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}		
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='16' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
	
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};	

		function CommaFormatted(amount){
		 
			var delimiter = ","; // replace comma if desired
			var a = amount.split('.',2);
			var d = a[1];
			var i = parseInt(a[0]);
			if(isNaN(i)) { return ''; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			var n = new String(i);
			var a = [];
			while(n.length > 3)
			{
				var nn = n.substr(n.length-3);
				a.unshift(nn);
				n = n.substr(0,n.length-3);
			}
			if(n.length > 0) { a.unshift(n); }
			n = a.join(delimiter);
			if(d.length < 1) { amount = n; }
			else { amount = n + '.' + d; }
			amount = minus + amount;
			return amount;
		}
		
		function checkInputValue(o){
			if (o.val().length < 1 ) {
					o.addClass( "ui-state-error" );
					return false;
				} else {
					o.removeClass( "ui-state-error" );
					return true;
				}
		}
		function checkInputAddCustomer( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				$(".validateTipsCust")
				.text( "Please input " + n + "." )
				.addClass( "ui-state-highlight" );
				setTimeout(function() {
					tips.removeClass( "ui-state-highlight", 1500 );
				}, 500 );
			 
				return false;
			} else {
				return true;
			}
		}
	
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputAddCustomer( Code, "Customer Code",1);
			bValid = bValid && checkInputAddCustomer( FirstName, "First name",1);
			bValid = bValid && checkInputAddCustomer( LastName, "Last name",1);
			bValid = bValid && checkInputAddCustomer( Address, "Address ",1);
			//bValid = bValid && checkRegexp( Email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. admin@oriental.com" );					
			bValid = bValid && checkInputAddCustomer( Telephone, "Telephone",1);
			
			return bValid;
		}
		
		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		//************************
		//>>> End Method & Function
		//***********************
		
		
		//****************************
		// Dialog 
		//****************************
		// Close Dialog 
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
		//Login Dialog
		$( "#dialog-Login" ).dialog({
			resizable: false,
			height:270,
			width:450,
			zIndex:9999,
			autoOpen: false,
			modal: true,
			open: function() { 
				modeLogin="discount";
				//$("#username").val('');
				//$("#password").val('');
				//$("#frmLogin").hide();
				//$("#frmSelectDiscount").show();
				//$( "#dialog-Login" ).dialog( "option", "height",360 );
			},
			close: function() {
				modeLogin="discount";
				$("#password").removeClass( "ui-state-error" );
				$("#username").removeClass( "ui-state-error" );
				//$("#frmLogin").hide();
				//$("#frmSelectDiscount").show();		
			}	
		});	
		//Discount special
		$( "#dialog-special" ).dialog({
			resizable: false,
			height:180,
			width:450,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			zIndex:9999,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-AddCust" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 500,
			width: 400,
			zIndex:9999,
			modal: true,
			open: function() { 
				addCustFields.val("");
			},
			close: function() {
				addCustFields.val( "" ).removeClass( "ui-state-error" );
			}
 		});
		
		//For inform user about credit sale , service
		$( "#dialog-alert" ).dialog({
			resizable: false,
			height:350,
			width: 450,
			zIndex:9999,
			autoOpen: false,
			modal: true,
			close: function() {
				$("#spInfo").attr('innerHTML','' );
				$( "#tbCourse tbody tr" ).remove();
			}
		});

		//Form customer Search    
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 450,
			width: 680,
			zIndex:9999,
			modal: true,
			open: function() { 
				$( "#tbNewProduct tbody tr" ).remove();
				allFields.val( "" );
				//}
			},
			close: function() {
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		//Form  Smart Purse 
		$( "#dialog-smartpurse" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 550,
			zIndex:9999,
			width: 550,
			modal: true,
			open: function() { 
				SmartFields.removeClass( "ui-state-error" );
				$("#SmartCustname").attr('innerHTML',$("#CustName").val());
				 $("#dialog-confirm p").attr('innerText','Are you sure this card?');
				$.post('a_customer.php'
						,{"m":"card","id":m_CustomerID}
						,function(data){
							//,{"m":"card","id":$("#custid").val()}
							$( "#tbNewSmart tbody:first" ).prepend(data);
						}
					);
				
			},
			close: function() {
				//alert('dd');
				 $( "#tbNewSmart tbody tr" ).remove();
				 SmartFields.val( "" ).removeClass( "ui-state-error" );
				  $("#dialog-confirm p").attr('innerText','Are you sure this product ?');
				 
			}
		});		
		function checkInputSmartPurse(){
			if (!(checkInputFile(SmartCardNo))){
				SmartCardNo.addClass( "ui-state-error" );
				updateTipsSmart( "Please input CardNo");
			}else if (!(checkInputFile(SmartAmount))){
				SmartAmount.addClass( "ui-state-error" );
				updateTipsSmart( "Please input Amount");
				return false;
			}else{
				SmartCardNo.removeClass( "ui-state-error" );
				SmartAmount.removeClass( "ui-state-error" );
				return true;
			}
		}
		function updateTipsSmart( t  ) {
			$("#validateTipsSmart")
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				$("#validateTipsSmart").removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}	
		$("#btnSmart").click(function(){
			var bValid=true;
			 bValid= checkInputSmartPurse();
			//return;
			if (bValid) {
				var m_obj={};
				m_obj["CardNo"]=SmartCardNo.val();
				m_obj["Amount"]=SmartAmount.val();
				m_obj["CustID"]=m_CustomerID;//$("#custid").val();
				
				$.post('a_customer.php',{"m":"addcard","var":m_obj,"id":0}, function(data){
					
					$( "#tbNewSmart tbody tr" ).remove();
					$( "#tbNewSmart tbody:first" ).prepend( data ); 
				});
				SmartFields.val("");
			}
			return true;
		});
		
		$("#btnRemove").live('click',function(){
			var cardid;
			rowSelect = $(this).parent().parent();
			cardid=$(this).parent().parent().find("td").eq(1).html();
			//alert(cardid);
			//alert(cardid);
			$("#mode").val("delcard");
			$("#dialog-confirm").dialog("open");
			$("#dialog-confirm").dialog("option","buttons",	{
				"Delete": function() {
					$.post('a_customer.php',{"m":"delcard","var":{"id":cardid},"id":0}, function(data){
							rowSelect.remove(); // remove row
							$("#dialog-confirm").dialog( "close" );
					});
				},
				Cancel: function() {
						$( this ).dialog( "close" );
				}
			});			
		});		
});
(function( $ ) {
		$.widget( "ui.combobox", {
		_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
									select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );
					
					input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			}
		});
})( jQuery );
